<template>
  <div>
    <div>
      <!-- 查询表单 -->
      <Form :model="dayForm" style="display: block;">
        <Row gutter="40">
          <i-col span="6">
            <FormItem>
              <Cascader
                change-on-select
                :data="organizationList"
                v-model="dayForm.organization"
                @on-change="organizationChange"
                placeholder="所属机构"
                clearable
              ></Cascader>
            </FormItem>
          </i-col>
          <i-col span="6">
            <FormItem>
              <Select
                v-model="dayForm.empolyee"
                placeholder="员工"
                :clearable="isClearable"
              >
                <Option
                  v-for="item in empolyeeList"
                  :key="item.key"
                  :value="item.key"
                  >{{ item.value }}-{{ item.key }}</Option
                >
              </Select>
            </FormItem>
          </i-col>
          <i-col span="6">
            <FormItem>
              <DatePicker
                type="daterange"
                placeholder="开始时间~结束时间"
                :editable="false"
                style="width: 100%"
                v-model="dayForm.dateRange"
              ></DatePicker>
            </FormItem>
          </i-col>
          <i-col span="6">
            <FormItem>
              <Select
                v-model="dayForm.role"
                placeholder="所属角色"
                :clearable="isClearable"
              >
                <Option
                  v-for="item in roleList"
                  :key="item.key"
                  :value="item.key"
                  >{{ item.value }}</Option
                >
              </Select>
            </FormItem>
          </i-col>
        </Row>
        <Row gutter="40">
          <i-col span="6">
            <FormItem>
              <Select
                v-model="dayForm.attendStatus"
                placeholder="考勤状态"
                clearable
              >
                <Option
                  v-for="item in attendStatusList"
                  :key="item.value"
                  :value="item.value"
                  >{{ item.label }}</Option
                >
              </Select>
            </FormItem>
          </i-col>
        </Row>
        <Row>
          <FormItem>
            <Button
              type="primary"
              style="margin-right: 20px"
              @click="handleSubmit(1)"
              >查询</Button
            >
            <Button @click="handleReset()" :disabled="resetButtonDisabled"
              >重置</Button
            >
          </FormItem>
        </Row>
      </Form>
      <!-- 查询出的数据 -->
      <Table :columns="dayColumns" :data="dayData">
        <template slot-scope="{ row }" slot="amStatus">
          <div v-if="row.amStatus == '正常'" style="color: #2d8cf0">正常</div>
          <span
            v-else
            style="color: red; cursor: pointer"
            @click="
              offWork = true;
              currentRow = row;
              modalData(row);
            "
            >{{ row.amStatus }}</span
          >
        </template>
        <template slot-scope="{ row }" slot="applyoffNo">
          <a @click="attendToApproval(row, 1)">{{ row.applyoffNo }}</a>
        </template>
        <template slot-scope="{ row }" slot="applyoutNo">
          <a @click="attendToApproval(row, 2)">{{ row.applyoutNo }}</a>
        </template>
        <template slot-scope="{ row }" slot="applyaddNo">
          <a @click="attendToApproval(row, 3)">{{ row.applyaddNo }}</a>
        </template>
      </Table>
      <!-- 分页 -->
      <Page
        :total="total"
        show-sizer
        show-total
        style="text-align: right; margin-top: 20px; margin-bottom: 30px"
        @on-change="pageChange"
        @on-page-size-change="pageSizeChange"
        :page-size-opts="pageSizeOptions"
        :current="pageIndex"
        :page-size="pageSize"
        transfer
      ></Page>
      <!-- 迟到、地点异常弹窗 -->
      <Modal
        footer-hide="true"
        :value="offWork"
        :mask-closable="false"
        @on-visible-change="modalVisibleChange"
        @on-cancel="modalCancel"
        width="900"
      >
        <span slot="header" style="color: #fff; font-size: 16px"
          >{{ currentRow.today }}&nbsp;&nbsp;打卡记录</span
        >
        <div class="modalContent">
          <div class="image">
            <!-- <img :src="headPortrait" /> -->
          </div>
          <div class="baseContent">
            <div class="name">{{ currentRow.uname }}</div>
            <div class="otherContent">
              所属机构：{{ currentRow.organization }}
              <span style="margin-left: 5px; margin-right: 5px">|</span>
              角色：{{ currentRow.urole }}
            </div>
          </div>
        </div>
        <span style="display: block; clear: both"></span>
        <Table width="100%" :columns="employeeColumns" :data="empolyeeData">
          <template slot-scope="{ row }" slot="statusDetail">
            <span
              :style="
                row.detail == '打卡地点正常,打卡时间正常' ? '' : 'color:red'
              "
              >{{ row.detail }}</span
            >
          </template>
        </Table>
      </Modal>
    </div>
  </div>
</template>

<script>
import { exportFile } from "../../../util/util";
import util from "../../../util/util";
export default {
  name: "attendRecord",
  props: {
    dayPass: {
      type: String,
    },
  },
  data() {
    return {
      dayForm: {
        organization: [],
        empolyee: "",
        dateRange: ["", ""],
        role: "",
        attendStatus: "",
      },
      organizationList: [],
      empolyeeList: [],
      roleList: [],
      attendStatusList: [
        {
          value: "0",
          label: "异常",
        },
        {
          value: "1",
          label: "正常",
        },
      ],
      dayColumns: [
        {
          title: "日期",
          key: "todays",
          width: "140",
          fixed: "left",
        },
        {
          title: "姓名",
          key: "uname",
          width: "150",
          fixed: "left",
        },
        {
          title: "工号",
          key: "uno",
          align: "center",
          width: "130",
        },
        {
          title: "所属机构",
          key: "organization",
          width: "250",
        },
        {
          title: "角色",
          key: "urole",
          width: "150",
        },
        {
          title: "上班打卡",
          key: "upTime",
          align: "center",
          width: "100",
        },
        {
          title: "下班打卡",
          key: "downTime",
          align: "center",
          width: "100",
        },
        {
          title: "考勤状态",
          key: "amStatus",
          align: "center",
          width: "250",
          slot: "amStatus",
        },
        {
          title: "关联请假单",
          key: "applyoffNo",
          align: "center",
          width: "190",
          slot: "applyoffNo",
        },
        {
          title: "关联外出单",
          key: "applyoutNo",
          align: "center",
          width: "190",
          slot: "applyoutNo",
        },
        {
          title: "关联补卡单",
          key: "applyaddNo",
          align: "center",
          minWidth: 190,
          slot: "applyaddNo",
        },
      ],
      dayData: [],
      offWork: false,
      currentRow: "",
      employeeColumns: [
        {
          title: "类型",
          key: "signType",
          width: "100",
        },
        {
          title: "打卡时间",
          key: "signTime",
          width: "120",
        },
        {
          title: "状态详情",
          key: "detail",
          width: "150",
          slot: "statusDetail",
        },
        {
          title: "地点",
          key: "site",
          width: "260",
        },
        {
          title: "设备",
          key: "equipment",
          width: "",
        },
      ],
      empolyeeData: [],
      total: "0",
      pageIndex: 1,
      pageSize: 10,
      pageSizeOptions: [5, 10, 15, 20],
      resetButtonDisabled: false,
      isClearable: true,
      pageObj: "",
      headPortrait: "",
      jsonData: {},
    };
  },
  methods: {
    //从searchDetails返回
    getSearchData() {
      let isreturn = sessionStorage.getItem("isreturn");
      let searchData = sessionStorage.getItem("searchData");
      if (isreturn && isreturn == "Y") {
        this.dayForm = JSON.parse(searchData);
        this.organizationChange([this.dayForm.organization]);
        this.dayForm = JSON.parse(searchData);
        // this.handleSubmit()
      }
    },
    Echo() {
      this.jsonData = util.GetRequest(decodeURI(location.hash)) || {};
      if (
        this.jsonData.endTime ||
        this.jsonData.starTime ||
        this.jsonData.uNo ||
        this.jsonData.status ||
        this.jsonData.uRole ||
        this.jsonData.index ||
        this.pageIndex != "1"
      ) {
        (this.dayForm.role = this.jsonData.uRole), //角色
          (this.dayForm.attendStatus = this.jsonData.status); //状态
        this.dayForm.empolyee = this.jsonData.uNo; //员工
        let arr1 = [];
        arr1.push(this.jsonData.starTime, this.jsonData.endTime);
        this.dayForm.dateRange = arr1;
        let arr = [];
        this.organizationList.forEach((one) => {
          if (one.value == this.jsonData.organization) {
            arr.push(one.value);
          } else if (one.children) {
            one.children.forEach((tow) => {
              if (tow.value == this.jsonData.organization) {
                arr.push(one.value, tow.value);
              } else if (tow.children) {
                tow.children.forEach((three) => {
                  if (three.value == this.jsonData.organization) {
                    arr.push(one.value, tow.value, three.value);
                  } else if (three.children) {
                    three.children.forEach((four) => {
                      if (three.value == this.jsonData.organization) {
                        arr.push(one.value, tow.value, three.value, four.value);
                      }
                    });
                  }
                });
              }
            });
          }
        });
        this.dayForm.organization = arr;
        console.log(arr, "arrrr222222");
        this.pageIndex = parseInt(this.jsonData.index);
        this.handleSubmit();
      } else {
        this.handleSubmit();
      }
    },
    //转时间
    timeFormat(time) {
      if (!time) {
        return "";
      }
      let d = new Date(time);
      var y = d.getFullYear();
      var m = d.getMonth() + 1;
      if (m < 10) {
        m = "0" + m;
      }
      var day = d.getDate();
      if (day < 10) {
        day = "0" + day;
      }
      return y + "-" + m + "-" + day;
    },

    // 重置
    handleReset() {
      // this.dayForm = {};
      // this.dayForm = {
      //   organization: [],
      //   empolyee: "",
      //   dateRange: ["", ""],
      //   role: "",
      //   attendStatus: "",

      // };

      Object.assign(this.$data, this.$options.data());
      this.pageIndex = 1;
      this.handleSubmit();
    },

    // 查询
    handleSubmit(e) {
      // this.pageIndex = 1;
      this.pageSize = 10;
      if (
        !this.dayForm.organization &&
        !this.dayForm.empolyee &&
        !this.dayForm.dateRange[0] &&
        !this.dayForm.role &&
        !this.dayForm.attendStatus
      ) {
        this.$Message.error("请至少选择一个条件");
        return;
      }
      let startDate = "";
      let endDate = "";
      if (this.dayForm.dateRange[0]) {
        // let date1 = new Date(this.dayForm.dateRange[0]).toJSON();
        // startDate = new Date(+new Date(date1) + 8 * 3600 * 1000).toISOString();
        // let date2 = new Date(this.dayForm.dateRange[1]).toJSON();
        // endDate = new Date(+new Date(date2) + 8 * 3600 * 1000).toISOString();

        startDate = this.timeFormat(this.dayForm.dateRange[0]);
        endDate = this.timeFormat(this.dayForm.dateRange[1]);
      }
      let obj = {
        organization:
          this.dayForm.organization[this.dayForm.organization.length - 1],
        uNo: this.dayForm.empolyee,
        starTime: startDate,
        endTime: endDate,
        uRole: this.dayForm.role,
        status: this.dayForm.attendStatus,
        index: e === 1 ? (this.pageIndex = 1) : this.pageIndex,
        pageSize: this.pageSize,
      };
      this.pageObj = obj;
      console.log(this.pageObj, "入参");
      this.$router.push({
        path: this.$router.path,
        query: this.pageObj,
      });
      console.log(this.pageObj, "入参");
      this.api.uerAttendanceDay(obj).then((res) => {
        if (res.code == 200 && res.data != null) {
          this.$emit("modifyDayFlag", false);
          this.dayData = [];
          res.data.records.forEach((element) => {
            if (element.today) {
              element.todays =
                element.today.substr(2, 8) +
                "星期" +
                "天一二三四五六".charAt(new Date(element.today).getDay());
            }
            if (element.upTime) {
              element.upTime = element.upTime.substr(0, 5);
            }
            if (element.downTime) {
              element.downTime = element.downTime.substr(0, 5);
            }
            this.dayData.push(element);
          });
          this.total = res.data.total;
          this.$Message.info(res.msg);
        } else {
          this.$emit("modifyDayFlag", true);
          this.dayData = [];
          this.total = 0;
          this.$Message.info(res.msg);
        }
      });
    },

    // 分页查询
    pageSubmit() {
      this.pageObj.index = this.pageIndex;
      this.pageObj.pageSize = this.pageSize;
      this.$router.push({
        path: this.$router.path,
        query: this.pageObj,
      });
      this.api.uerAttendanceDay(this.pageObj).then((res) => {
        if (res.code == 200 && res.data != null) {
          this.dayData = [];
          res.data.records.forEach((element) => {
            if (element.today) {
              element.todays =
                element.today.substr(2, 8) +
                "星期" +
                "天一二三四五六".charAt(new Date(element.today).getDay());
            }
            if (element.upTime) {
              element.upTime = element.upTime.substr(0, 5);
            }
            if (element.downTime) {
              element.downTime = element.downTime.substr(0, 5);
            }
            this.dayData.push(element);
          });
          this.total = res.data.total;
        } else {
          this.dayData = [];
          this.total = 0;
          this.$Message.info(res.msg);
        }
      });
    },

    // 对话框关闭设置
    modalVisibleChange(bool) {
      if (bool == false) {
        this.offWork = false;
      }
    },

    // 分页设置
    pageChange(pageIndex) {
      this.pageIndex = pageIndex;
      this.pageSubmit();
    },
    pageSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.pageSubmit();
    },

    // 当天打卡详情
    async modalData(row) {
      this.headPortrait = "";
      let obj1 = {
        no: row.uno,
      };
      this.api.getUserChatHeadByNo(obj1).then((res) => {
        if (res.code == 200 && res.data != null) {
          this.headPortrait = res.data;
        }
      });
      if (row.amAttendanceDeatilID) {
        let obj = {
          id: row.amAttendanceDeatilID.toString(),
        };
        await $.ajax("scrm-gateway/scrm-uer/api/UerAttendanceDetail/" + obj.id, {
          method: "get",
          contentType: "application/json;charset=utf-8",
          beforeSend: function (xhr) {
            xhr.setRequestHeader(
              "Authorization",
              sessionStorage.getItem("credentials")
            );
          },
          success: (res) => {
            if (res.data != null) {
              res.data.forEach((element) => {
                element.signType = "上班打卡";
                element.signTime = element.signTime.substr(11, 5);
                this.empolyeeData.push(element);
                // this.empolyeeData=[{}]
                // this.empolyeeData[0] = element
              });
            }
          },
        });
      }
      if (row.pmAttendanceDeatilID) {
        let obj2 = {
          id: row.pmAttendanceDeatilID.toString(),
        };
        $.ajax("scrm-gateway/scrm-uer/api/UerAttendanceDetail/" + obj2.id, {
          method: "get",
          contentType: "application/json;charset=utf-8",
          beforeSend: function (xhr) {
            xhr.setRequestHeader(
              "Authorization",
              sessionStorage.getItem("credentials")
            );
          },
          success: (res) => {
            if (res.data != null) {
              res.data.forEach((element) => {
                element.signType = "下班打卡";
                element.signTime = element.signTime.substr(11, 5);
                // if(row.amAttendanceDeatilID){
                //   this.empolyeeData[1] = element;
                // }else{
                this.empolyeeData.push(element);
                // }
              });
            }
          },
        });
      }
    },

    // modal关闭
    modalCancel() {
      this.empolyeeData = [];
    },

    // 转到详情页
    attendToApproval(row, index) {
      if (index == 1) {
        row.applyNo = row.applyoffNo;
      } else if (index == 2) {
        row.applyNo = row.applyoutNo;
      } else if (index == 3) {
        row.applyNo = row.applyaddNo;
      }
      let newtemp = JSON.parse(JSON.stringify(this.dayForm));
      newtemp.dateRange = [
        this.timeFormat(this.dayForm.dateRange[0]),
        this.timeFormat(this.dayForm.dateRange[1]),
      ];
      sessionStorage.setItem("searchData", JSON.stringify(newtemp));
      this.$router.push({
        path: "/U/systemManagement/approvalDetails",
        query: {
          item: row,
        },
      });
    },

    // 导出表格
    exportExcel() {
      if (
        !this.dayForm.organization &&
        !this.dayForm.empolyee &&
        !this.dayForm.dateRange[0] &&
        !this.dayForm.role &&
        !this.dayForm.attendStatus
      ) {
        this.$Message.error("请至少选择一个条件");
        return;
      }
      let startDate = "";
      let endDate = "";
      if (this.dayForm.dateRange[0] != "") {
        let date1 = new Date(this.dayForm.dateRange[0]).toJSON();
        startDate = new Date(+new Date(date1) + 8 * 3600 * 1000).toISOString();
        let date2 = new Date(this.dayForm.dateRange[1]).toJSON();
        endDate = new Date(+new Date(date2) + 8 * 3600 * 1000).toISOString();
      }
      let obj = {
        organization:
          this.dayForm.organization[this.dayForm.organization.length - 1],
        uNo: this.dayForm.empolyee,
        starTime: startDate,
        endTime: endDate,
        uRole: this.dayForm.role,
        status: this.dayForm.attendStatus,
      };

      exportFile("scrm-gateway/scrm-uer/api/export/uerAttendanceExport", obj);

      // let url = "../rest/export/uerAttendanceExport";
      // window.open(
      //   url +
      //     "?organization=" +
      //     obj.organization +
      //     "&uNo=" +
      //     obj.uNo +
      //     "&starTime=" +
      //     obj.starTime +
      //     "&endTime=" +
      //     obj.endTime +
      //     "&uRole=" +
      //     obj.uRole +
      //     "&status=" +
      //     obj.status
      // );
    },

    // 获取当前机构及以下
    getOrganizationList() {
      this.api.remanagecomList().then((res) => {
        if (res.code == 200 && res.data != null) {
          let arr = [];
          arr.push(res.data);
          arr.forEach((one) => {
            one.value = one.comcode;
            one.label = one.comcode + "-" + one.name;
            one.children = one.chilDren || [];
            if (one.children) {
              one.chilDren.forEach((two) => {
                two.value = two.comcode;
                two.label = two.comcode + "-" + two.name;
                two.children = two.chilDren || [];
                if (two.children) {
                  two.children.forEach((three) => {
                    three.value = three.comcode;
                    three.label = three.comcode + "-" + three.name;
                    three.children = three.chilDren || [];
                    if (three.children) {
                      three.children.forEach((four) => {
                        four.value = four.comcode;
                        four.label = four.comcode + "-" + four.name;
                        four.children = four.chilDren || [];
                      });
                    }
                  });
                }
              });
            }
          });
          console.log(arr);
          this.organizationList = arr;
          this.Echo();
        } else {
          this.organizationList = [];
        }
      });
      this.api.organizationDict().then((res) => {
        if (res.code == 200 && res.data != null) {
          let a = JSON.stringify(res.data[0].map);
          if (a !== "{}") {
            let b = a.substr(1, a.length - 2);
            let c = b.split(",");
            c.forEach((element) => {
              let d = element.split(":");
              this.roleList.push({
                key: d[0].replace(/\"/g, ""),
                value: d[1].replace(/\"/g, ""),
              });
            });
          }
          // if (res.data[0].listKeyValueVOS.length > 0) {
          //   this.organizationList = res.data[0].listKeyValueVOS;
          // }
          // 角色是外勤的处理
          if (this.roleList.length == 1 && this.roleList[0].key == 1) {
            this.isClearable = false;
            this.resetButtonDisabled = true;
            this.dayForm.organization = this.organizationList[0].value;
            this.organizationChange([this.dayForm.organization]);
            this.dayForm.role = this.roleList[0].key;
          }
        } else {
          this.$Message.error(res.msg);
        }
      });
    },

    // 机构改变，查询员工
    organizationChange(value) {
      if (value) {
        this.dayForm.empolyee = "";
        if (value) {
          let obj = {
            managecom: value,
          };
          $.ajax("scrm-gateway/scrm-uer/api/uerList/selectuser/" + value[value.length - 1], {
            method: "get",
            contentType: "application/json;charset=utf-8",
            beforeSend: function (xhr) {
              xhr.setRequestHeader(
                "Authorization",
                sessionStorage.getItem("credentials")
              );
            },
            success: (res) => {
              if (res.data.length > 0) {
                this.empolyeeList = res.data;
                if (this.roleList.length == 1 && this.roleList[0].key == 1) {
                  this.dayForm.empolyee = this.empolyeeList[0].key;
                }
              } else {
                this.empolyeeList = [];
              }
            },
            error: (res) => {
              this.$Message.error(res.msg);
            },
          });
        }
      } else {
        this.empolyeeList = [];
        this.dayForm.empolyee = "";
      }
    },
  },
  watch: {
    dayPass: function (val, oldVal) {
      this.exportExcel();
    },
  },
  mounted() {
    this.getSearchData();
    this.getOrganizationList();
  },
  beforeDestroy() {
    this.dayForm = null;
    this.organizationList = null;
    this.empolyeeList = null;
    this.roleList = null;
    this.attendStatusList = null;
    this.dayColumns = null;
    this.dayData = null;
    this.offWork = null;
    this.currentRow = null;
    this.employeeColumns = null;
    this.empolyeeData = null;
    this.total = null;
    this.pageIndex = null;
    this.pageSize = null;
    this.pageSizeOptions = null;
    this.resetButtonDisabled = null;
    this.isClearable = null;
    this.pageObj = null;
    this.headPortrait = null;
  },
};
</script>

<style lang="less" scoped>
@import "./dayCount.less";
</style>

<style>
.ivu-modal-header {
  background-color: #2d8cf0;
}
.ivu-modal-close .ivu-icon-ios-close {
  color: #fff !important;
}
.ivu-icon-ios-close:before {
  color: #fff !important;
}
</style>
